package com.right.netty.codes;

import com.right.factory.NodeStatus;
import com.right.util.Crc16;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;

/**********************************************
 * @author pillar
 * @date 2018/3/22
 **********************************************/
@ChannelHandler.Sharable
@Slf4j
public class PackageEncoder extends MessageToByteEncoder<String> {

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        if (StringUtils.isEmpty(NodeStatus.getInstance().getLockNo(ctx.channel()))){
            msg = "**"+ ","+msg+","+ Crc16.createCrc(msg.getBytes()) + "&&";
        }else {
            msg = "**"+ NodeStatus.getInstance().getLockNo(ctx.channel())+","+msg+","+ Crc16.createCrc(msg.getBytes()) + "&&";
        }
        out.writeBytes(msg.getBytes(Charset.forName("UTF-8")));

        log.info("send to lock={}",msg);

    }
}
